<template>
  <el-dialog v-model="state.dialogVisible" :title="state.dialogTitle" width="800px">
    <el-form :model="state.form" :rules="state.rules" ref="formRef" label-width="120px">
      <el-row :gutter="20">
        <el-col :span="24">
          <el-form-item label="订单信息" prop="orderInfo">
            <el-descriptions :column="2" border>
              <el-descriptions-item label="订单号">{{ state.form.orderCode }}</el-descriptions-item>
              <el-descriptions-item label="商品名称">{{ state.form.goodsName }}</el-descriptions-item>
              <el-descriptions-item label="数量">{{ state.form.quantity }}</el-descriptions-item>
              <el-descriptions-item label="当前状态">{{ state.form.currentStatus }}</el-descriptions-item>
            </el-descriptions>
          </el-form-item>
        </el-col>
        
        <el-col :span="12">
          <el-form-item label="仓库" prop="warehouseId">
            <el-select v-model="state.form.warehouseId" placeholder="请选择仓库" clearable filterable @change="onWarehouseChange">
              <el-option 
                v-for="warehouse in state.warehouseList" 
                :key="warehouse.id" 
                :label="warehouse.name" 
                :value="warehouse.id" 
              />
            </el-select>
          </el-form-item>
        </el-col>
        
        <el-col :span="12">
          <el-form-item label="库位" prop="locationId">
            <el-select v-model="state.form.locationId" placeholder="请选择库位" clearable filterable :disabled="!state.form.warehouseId">
              <el-option 
                v-for="location in state.locationList" 
                :key="location.id" 
                :label="location.name" 
                :value="location.id" 
              />
            </el-select>
          </el-form-item>
        </el-col>
        
        <el-col :span="12">
          <el-form-item label="出库数量" prop="outboundQuantity">
            <el-input-number 
              v-model="state.form.outboundQuantity" 
              :min="1" 
              :max="Math.max(state.form.quantity, 1)" 
              placeholder="请输入出库数量"
              style="width: 100%"
            />
          </el-form-item>
        </el-col>
        
        <el-col :span="12">
          <el-form-item label="出库类型" prop="outboundType">
            <el-select v-model="state.form.outboundType" placeholder="请选择出库类型" clearable>
              <el-option label="销售出库" value="sales" />
              <el-option label="退货出库" value="return" />
              <el-option label="调拨出库" value="transfer" />
              <el-option label="其他出库" value="other" />
            </el-select>
          </el-form-item>
        </el-col>
        
        <el-col :span="12">
          <el-form-item label="出库金额" prop="outboundAmount">
            <el-input-number 
              v-model="state.form.outboundAmount" 
              :min="0" 
              :precision="2"
              placeholder="请输入出库金额"
              style="width: 100%"
            />
          </el-form-item>
        </el-col>
        
        <el-col :span="12">
          <el-form-item label="客户名称" prop="customerName">
            <el-input 
              v-model="state.form.customerName" 
              placeholder="请输入客户名称"
            />
          </el-form-item>
        </el-col>
        
        <el-col :span="12">
          <el-form-item label="联系人" prop="contactPerson">
            <el-input 
              v-model="state.form.contactPerson" 
              placeholder="请输入联系人"
            />
          </el-form-item>
        </el-col>
        
        <el-col :span="12">
          <el-form-item label="联系方式" prop="contactMethod">
            <el-input 
              v-model="state.form.contactMethod" 
              placeholder="请输入联系方式"
            />
          </el-form-item>
        </el-col>
        
        <el-col :span="24">
          <el-form-item label="备注" prop="remark">
            <el-input 
              v-model="state.form.remark" 
              type="textarea" 
              :rows="3" 
              placeholder="请输入备注信息"
            />
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="handleClose">取消</el-button>
        <el-button type="primary" @click="handleConfirm" :loading="state.loading">确认出库</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script lang="ts" setup name="outboundDialog">
import { ref, reactive, onMounted } from 'vue';
import { ElMessage } from 'element-plus';
import { useSysoutstockorderApi } from '/@/api/OutWarehou/sysoutstockorder';
import { useWarehouseModelApi } from '/@/api/interacting/warehouse/warehouseModel';
import { useWarePlaceModelApi } from '/@/api/interacting/warehouse/warePlaceModel';

const emit = defineEmits(['confirm', 'cancel']);

const outstockApi = useSysoutstockorderApi();
const warehouseApi = useWarehouseModelApi();
const warePlaceApi = useWarePlaceModelApi();
const formRef = ref();
const state = reactive({
  dialogVisible: false,
  dialogTitle: '出库操作',
  loading: false,
  warehouseList: [] as any[],
  locationList: [] as any[],
  form: {
    orderId: null,
    orderCode: '',
    goodsName: '',
    quantity: 0,
    amount: 0,
    currentStatus: '',
    warehouseId: null,
    locationId: null,
    outboundQuantity: 0,
    outboundAmount: 0,
    outboundType: 'sales',
    customerName: '',
    contactPerson: '',
    contactMethod: '',
    remark: ''
  },
  rules: {
    warehouseId: [
      { required: true, message: '请选择仓库', trigger: 'change' }
    ],
    locationId: [
      { required: true, message: '请选择库位', trigger: 'change' }
    ],
    outboundQuantity: [
      { required: true, message: '请输入出库数量', trigger: 'blur' },
      { type: 'number', min: 1, message: '出库数量必须大于0', trigger: 'blur' }
    ],
    outboundAmount: [
      { required: true, message: '请输入出库金额', trigger: 'blur' },
      { type: 'number', min: 0, message: '出库金额不能小于0', trigger: 'blur' }
    ],
    customerName: [
      { required: true, message: '请输入客户名称', trigger: 'blur' }
    ],
    contactPerson: [
      { required: true, message: '请输入联系人', trigger: 'blur' }
    ],
    contactMethod: [
      { required: true, message: '请输入联系方式', trigger: 'blur' }
    ],
    outboundType: [
      { required: true, message: '请选择出库类型', trigger: 'change' }
    ]
  }
});

// 打开对话框
const openDialog = (orderData: any) => {
  state.dialogVisible = true;
  state.form = {
    orderId: orderData.id,
    orderCode: orderData.code,
    goodsName: orderData.goodsName,
    quantity: orderData.itemQuantity || orderData.salesQuantity || orderData.returnQuantity || orderData.salesReturnQuantity || 0,
    amount: orderData.itemAmount || orderData.salesAmount || orderData.returnAmount || orderData.salesReturnAmount || 0,
    currentStatus: orderData.documentStatus,
    warehouseId: null,
    locationId: null,
    outboundQuantity: orderData.itemQuantity || orderData.salesQuantity || orderData.returnQuantity || orderData.salesReturnQuantity || 0,
    outboundAmount: orderData.itemAmount || orderData.salesAmount || orderData.returnAmount || orderData.salesReturnAmount || 0,
    outboundType: 'sales',
    customerName: orderData.customerName || orderData.supplier || '',
    contactPerson: orderData.contactPerson || '',
    contactMethod: orderData.contactMethod || '',
    remark: ''
  };
  
  // 根据订单类型设置出库类型
  if (orderData.code?.includes('XSDH')) {
    state.form.outboundType = 'sales';
  } else if (orderData.code?.includes('XSTHDH')) {
    state.form.outboundType = 'return';
  }
  
  loadWarehouseList();
};

// 加载仓库列表
const loadWarehouseList = async () => {
  try {
    const res = await warehouseApi.page({
      page: 1,
      pageSize: 1000, // 获取所有仓库
      wareType: true // 只获取启用的仓库
    });
    
    // 转换数据格式
    state.warehouseList = (res.data?.result?.items || res.data?.result || []).map((warehouse: any) => ({
      id: warehouse.id,
      name: warehouse.wareName,
      code: warehouse.wareCode,
      address: warehouse.wareAddr
    }));
  } catch (error) {
    console.error('加载仓库列表失败:', error);
    ElMessage.error('加载仓库列表失败');
    // 如果API调用失败，使用空数组
    state.warehouseList = [];
  }
};

// 仓库变化时加载库位列表
const onWarehouseChange = async (warehouseId: any) => {
  state.form.locationId = null;
  state.locationList = [];
  
  if (!warehouseId) return;
  
  try {
    const res = await warePlaceApi.page({
      page: 1,
      pageSize: 1000, // 获取所有库位
      warehouseId: warehouseId, // 按仓库ID筛选库位
      warePlaceType: true // 只获取启用的库位
    });
    
    // 转换数据格式
    state.locationList = (res.data?.result?.items || res.data?.result || []).map((location: any) => ({
      id: location.id,
      name: location.warePlaceName,
      code: location.warePlaceCode,
      volume: location.warePlaceVolume
    }));
  } catch (error) {
    console.error('加载库位列表失败:', error);
    ElMessage.error('加载库位列表失败');
    // 如果API调用失败，使用空数组
    state.locationList = [];
  }
};

// 确认出库
const handleConfirm = async () => {
  if (!formRef.value) return;
  
  try {
    await formRef.value.validate();
    state.loading = true;
    
    // 生成出库单号
    const outstockCode = `CKDH${Date.now()}`;
    
    // 获取仓库名称
    const selectedWarehouse = state.warehouseList.find(w => w.id === state.form.warehouseId);
    const warehouseName = selectedWarehouse?.name || '未知仓库';
    
    // 获取出库类型中文名称
    const outboundTypeMap: { [key: string]: string } = {
      'sales': '销售出库',
      'return': '退货出库',
      'transfer': '调拨出库',
      'other': '其他出库'
    };
    const outboundTypeName = outboundTypeMap[state.form.outboundType] || '销售出库';
    
    // 调用出库单表API添加记录
    await outstockApi.add({
      code: outstockCode,
      outType: outboundTypeName,
      documentStatus: 6, // 已完成状态
      outDate: new Date().toISOString().split('T')[0],
      warehouseName: warehouseName,
      relatedCode: state.form.orderCode,
      customerName: state.form.customerName,
      contactPerson: state.form.contactPerson,
      contactMethod: state.form.contactMethod,
      goodsName: state.form.goodsName,
      outQuantity: state.form.outboundQuantity,
      outbouAmount: state.form.outboundAmount,
      warePlaceId: state.form.locationId, // 库位ID
      remark: state.form.remark || `来源于订单：${state.form.orderCode}`
    });
    
    ElMessage.success('出库操作成功，已生成出库单');
    emit('confirm', {
      ...state.form,
      outstockCode: outstockCode
    });
    handleClose();
  } catch (error) {
    console.error('出库操作失败:', error);
    ElMessage.error('出库操作失败');
    // 即使操作失败，也要关闭弹窗
    handleClose();
  } finally {
    state.loading = false;
  }
};

// 关闭对话框
const handleClose = () => {
  state.dialogVisible = false;
  state.form = {
    orderId: null,
    orderCode: '',
    goodsName: '',
    quantity: 0,
    amount: 0,
    currentStatus: '',
    warehouseId: null,
    locationId: null,
    outboundQuantity: 0,
    outboundAmount: 0,
    outboundType: 'sales',
    customerName: '',
    contactPerson: '',
    contactMethod: '',
    remark: ''
  };
  emit('cancel');
};

defineExpose({
  openDialog
});
</script>

<style scoped>
.dialog-footer {
  text-align: right;
}
</style>
